﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

using BodaNetCommunications.Utilities.ComTypes;

namespace BodaNetCommunications.Utilities.DataLibs
{
    public class ShortLib
    {
        public static short GetShortFromByteArray(byte[] source, int start = 0, EndianType dataFormat = EndianType.ABCD)
        {
            return BitConverter.ToInt16(ByteArrayLib.Get2ByteArray(source, start, dataFormat), 0);
        }

        public static short[] GetShortArrayFromByteArray(byte[] source, EndianType type = EndianType.ABCD)
        {
            short[] array = new short[source.Length / 2];
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = GetShortFromByteArray(source, i * 2, type);
            }

            return array;
        }

        public static short[] GetShortArrayFromString(string val)
        {
            List<short> list = new List<short>();
            if (val.Contains(' '))
            {
                string[] array = Regex.Split(val, "\\s+", RegexOptions.IgnoreCase);
                string[] array2 = array;
                foreach (string value in array2)
                {
                    list.Add(Convert.ToInt16(value));
                }
            }
            else
            {
                list.Add(Convert.ToInt16(val));
            }

            return list.ToArray();
        }

        public static short SetbitValueFromShort(short value, int bit, bool val, EndianType dataFormat = EndianType.ABCD)
        {
            byte[] byteArrayFromShort = ByteArrayLib.GetByteArrayFromShort(value, dataFormat);
            if (bit >= 0 && bit <= 7)
            {
                byteArrayFromShort[1] = ByteLib.SetbitValue(byteArrayFromShort[1], bit, val);
            }
            else
            {
                byteArrayFromShort[0] = ByteLib.SetbitValue(byteArrayFromShort[0], bit - 8, val);
            }

            return GetShortFromByteArray(byteArrayFromShort, 0, dataFormat);
        }

        public static short SetbitValueFrom2ByteArray(byte[] bt, int bit, bool val, EndianType dataFormat = EndianType.ABCD)
        {
            if (bit >= 0 && bit <= 7)
            {
                bt[1] = ByteLib.SetbitValue(bt[1], bit, val);
            }
            else
            {
                bt[0] = ByteLib.SetbitValue(bt[0], bit - 8, val);
            }

            return GetShortFromByteArray(bt, 0, dataFormat);
        }
    }
}